import React, { useState, useRef } from "react";

function MicrophoneAudioRecorder() {
    const [isRecording, setIsRecording] = useState(false);
    const [audioUrl, setAudioUrl] = useState(null);
    const mediaRecorderRef = useRef(null);
    const audioChunksRef = useRef([]);

    // 开始录音
    const startRecording = async () => {
        try {
            // 获取麦克风权限并捕获音频流
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            const mediaRecorder = new MediaRecorder(stream);

            // 初始化音频块，用于存储录制数据
            audioChunksRef.current = [];
            mediaRecorderRef.current = mediaRecorder;

            // 捕获音频数据块
            mediaRecorder.ondataavailable = (event) => {
                audioChunksRef.current.push(event.data);
            };

            // 录制停止后生成音频 Blob
            mediaRecorder.onstop = () => {
                const audioBlob = new Blob(audioChunksRef.current, { type: "audio/webm" });
                const formData = new FormData();
                const audioFile = new File([audioBlob], "recording.webm", { type: "audio/webm" });
                formData.append("file", audioFile); // 将音频文件添加到 FormData 中

                //此处可以提交录音


                const audioUrl = URL.createObjectURL(audioBlob);
                setAudioUrl(audioUrl); // 将生成的音频 URL 设置为状态
            };

            // 开始录制
            mediaRecorder.start();
            setIsRecording(true);
        } catch (err) {
            console.error("Error accessing microphone: ", err);
        }
    };

    // 停止录音
    const stopRecording = () => {
        if (mediaRecorderRef.current) {
            mediaRecorderRef.current.stop();
            setIsRecording(false);
        }
    };

    return (
        <div className="flex flex-col items-center p-4">


            {/* 控制按钮 */}
            <div className="mb-4">
                {isRecording ? (
                    <button
                        onClick={stopRecording}
                        className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-700"
                    >
                        停止录音
                    </button>
                ) : (
                    <button
                        onClick={startRecording}
                        className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-700"
                    >
                        开始录音
                    </button>
                )}
            </div>

            {/* 播放录制的音频 */}
            {audioUrl && (
                <div className="mt-4">
                    <h2 className="text-lg font-semibold mb-2">录制结果:</h2>
                    <audio controls src={audioUrl} className="mb-2"></audio>
                    <a
                        href={audioUrl}
                        download="recording.webm"
                        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700"
                    >
                        下载音频
                    </a>
                </div>
            )}
        </div>
    );
}

export default MicrophoneAudioRecorder;